/**
 * 
 */
package com.ccqlk.attendance.api;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.Model;

/**
 * Copyright 2015-2018 重庆鲁控科技有限公司<br>
 * 文件标题: APIBaseController<br>
 * 文件说明: API基础控制类<br>
 * @author ZhangYinxian 348893009@qq.com<br>
 * 创建时间 2016年5月27日 下午5:13:10<br>
 */
public class APIBaseController {

	public static final String API_VERSION = "api/1_0";
	
	protected Model render(HttpServletRequest request, HttpServletResponse response, Model model, List<?> list) {
		if (list != null) {
			model.addAttribute("list", list);
			return renderSuccess(request, response, model);
		} else {
			return renderFail(request, response, model);
		}
	}

	protected Model renderSuccess(HttpServletRequest request, HttpServletResponse response, Model model) {
		return renderSuccess(request, response, model, "成功");
	}

	protected Model renderSuccess(HttpServletRequest request, HttpServletResponse response, Model model, String msg) {
		model.addAttribute("success", true);
		model.addAttribute("message", msg);
		return render(request, response, model);
	}

	protected Model renderFail(HttpServletRequest request, HttpServletResponse response, Model model) {
		return renderFail(request, response, model, "获取数据失败");
	}

	protected Model renderFail(HttpServletRequest request, HttpServletResponse response, Model model, String msg) {
		model.addAttribute("success", false);
		model.addAttribute("message", StringUtils.isEmpty(msg) ? "获取数据失败" : msg);
		return render(request, response, model);
	}

	protected Model render(HttpServletRequest request, HttpServletResponse response, Model model) {
		if (request.getHeader("Origin") != null) {
			response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
		}
		response.setHeader("Access-Control-Allow-Credentials", "true");
		return model;
	}
}
